// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.tcmdb.rest.service;

import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.servicezombie.cxf.JaxbUnmarshallerFascade;
import de.servicezombie.cxf.WebserviceTemplate;
import de.servicezombie.cxf.WebserviceTemplateFactory;
import de.servicezombie.tcmdb.dao.mongo.AuthorDao;
import de.servicezombie.tcmdb.dao.mongo.MongoUtils;
import de.servicezombie.tcmdb.rest.RestPathUtils;
import de.servicezombie.tcmdb.rest.RestTransformerSupport;
import de.servicezombie.tcmdb.rest.SameInstanceTransformer;
import de.servicezombie.tcmdb.rest.vo.WsAuthor;
import de.servicezombie.tcmdb.rest.vo.WsListResult;

public class AuthorServiceRestImpl implements AuthorService {

	private static final Logger log = LoggerFactory.getLogger(AuthorServiceRestImpl.class);

	private AuthorDao authorDao;
	private JaxbUnmarshallerFascade unmarshallerFascade;

	public void setUnmarshallerFascade(JaxbUnmarshallerFascade unmarshallerFascade) {
		this.unmarshallerFascade = unmarshallerFascade;
	}
	
	public void setAuthorDao(AuthorDao authorDao) {
		this.authorDao = authorDao;
	}

	@Override
	public void getActiveAuthors() {

		if (log.isDebugEnabled()) {
			log.debug("findActiveApplication: >> ");
		}

		List<WsAuthor> dbResult = authorDao.findAll();
		WsListResult<WsAuthor> wsResult = new RestTransformerSupport().toWsListResult(
				dbResult, new SameInstanceTransformer<WsAuthor>());

		if (log.isDebugEnabled()) {
			log.debug("findActiveApplication: << " + wsResult);
		}
		WebserviceTemplate template = new WebserviceTemplateFactory().build();
		template.getWebserviceResponse().setBody(wsResult);
	}

	@Override
	public void saveAuthor(String authorId, InputStream input) {
		
		if (log.isDebugEnabled()) {
			log.debug("saveAuthor: >> " + authorId);
		}
		
		WsAuthor author = unmarshallerFascade.unmarshall(input, WsAuthor.class);		
		MongoUtils.invalidateId(author);
		
		WsAuthor authorFromDb = null;
		if(!RestPathUtils.isNewRecordRequested(authorId)) {
			authorFromDb = authorDao.load(authorId);
			author.setId(authorFromDb.getId());
		}
				
		author = authorDao.saveNewOrReplace(author);
		
		if (log.isDebugEnabled()) {
			log.debug("saveAuthor: << " + author);
		}
		
		WebserviceTemplate template = new WebserviceTemplateFactory().build();
		template.getWebserviceResponse().setBody(author);
	}

}
